#!/usr/bin/env python3
"""Fetch World Bank data using wbgapi and save to CSV.

Usage examples:
  # default (China & USA GDP 2010-2023)
  ./scripts/fetch_wb.py

  # custom
  ./scripts/fetch_wb.py --indicator NY.GDP.MKTP.CD --countries CHN USA BRA --start 2000 --end 2022 --out data/gdp.csv

"""
import os
import argparse
import wbgapi as wb


def fetch_save(indicator, countries, start, end, outpath):
    os.makedirs(os.path.dirname(outpath) or '.', exist_ok=True)
    print(f"Fetching indicator={indicator} countries={countries} years={start}-{end}...")
    try:
        df = wb.data.DataFrame(indicator, economy=countries, time=range(start, end + 1))
        if df.empty:
            print("Warning: returned DataFrame is empty")
        df.to_csv(outpath)
        print(f"Saved {outpath} (shape={df.shape})")
    except Exception as e:
        print(f"Failed to fetch data: {e}")
        raise


def parse_args():
    p = argparse.ArgumentParser(description='Fetch World Bank data and save CSV')
    p.add_argument('--indicator', '-i', default='NY.GDP.MKTP.CD', help='World Bank indicator ID (default GDP current USD)')
    p.add_argument('--countries', '-c', nargs='+', default=['CHN', 'USA'], help='List of country ISO codes (default CHN USA)')
    p.add_argument('--start', type=int, default=2010, help='Start year (inclusive)')
    p.add_argument('--end', type=int, default=2023, help='End year (inclusive)')
    p.add_argument('--out', '-o', default='data/gdp_china_usa_2010_2023.csv', help='Output CSV path')
    return p.parse_args()


def main():
    args = parse_args()
    fetch_save(args.indicator, args.countries, args.start, args.end, args.out)


if __name__ == '__main__':
    main()
